﻿var iCurrentALImage=0;
var iCountALImage=0;

//Generuje unikalny ID dla tagow html
function GenerateUniqueID()
{
	return ("guid_" + (new Date()).getTime());
}

//Okno dialogowe do potwierdzania akcji
//cookie - id tagu wzgledem ktorego obliczana jest pozycja okna, 
//str - tresc w oknie
//title - tekst na belke okna
//bLoad - 
//min_width - 
//min_height -
//callback - funkcja ktora jest wywolywana gdy zostal nacisniety przycisk potwierdzenia
function ConfrimDialog(cookie,str,title,bLoad,min_width,min_height,callback)
{
	var id=GenerateUniqueID();	
	var id_ok=GenerateUniqueID()+'ok';
	var id_cancel=GenerateUniqueID()+'cancel';
	var faktor=min_width/min_height;
		
		
	$("body").append('\
		<div class="fullconfrim">\
		<div class="fullscreendivbackground"></div>\
		<div id="'+id+'" class="confrim_dialog">\
		<div class="confrim_dialog_inside">\
		<div class="confrim_dialog_title">'+title+'</div>\
		<div class="confrim_dialog_body">'
		+str+
		'</div>\
		<div class="confrim_dialog_button_bar">\
		<input class="confrim_dialog_button" id="'+id_ok+'" type="button" value="Tak" />\
		<input class="confrim_dialog_button" id="'+id_cancel+'" type="button" value="Nie" />\
		</div>\
		</div>\
		</div>\
		</div>');	
	
	var iWidth=Math.max($("#"+id).width(),min_width);
	var iHeight=Math.max($("#"+id).height(),min_height);
	
	 var halfsc = $(window).height()/2;
	 var halfscrn = $(window).width()/2;
	
	$(".fullscreendivbackground").height($("body").height()+80);
	
	
	$("#"+id).offset({ top: (halfsc-iHeight/2)+$(window).scrollTop(), left: (halfscrn-iWidth/2) });
	
	$("#"+id).width(iWidth);
	$("#"+id).height(iHeight);
	
	$("#"+id_ok).click(function()
	{
		var jObj=$(this).parents(".fullconfrim");
		
		if(bLoad)
		{
			jObj.find('.confrim_dialog_body').html('<img src="/images/board/load_more.gif" />');
			jObj.find("#"+id_cancel).hide();
			$(this).hide();
		}else
			$(this).parents(".fullconfrim").remove();
			
		callback(cookie);
		
		if(bLoad)
			$(this).parents(".fullconfrim").remove();
	});
	
	$("#"+id_cancel).click(function()
	{
		$(this).parents(".fullconfrim").remove();
	});
}


function OnMouseOverStatus()
{	
	$(this).find('.board_exe_ShowContextMenu').show();
	$(this).find('.board_show_commets').removeClass('board_show_commets').addClass('board_show_commets_activ');
}

function OnMouseOutStatus()
{	
	$(this).find('.board_exe_ShowContextMenu').hide();
	$(this).find('.board_show_commets_activ').addClass('board_show_commets').removeClass('board_show_commets_activ');
}

function OnMouseOverComment()
{	
	$(this).find('.board_exe_ShowContextMenuComment').show();
}

function OnMouseOutComment()
{	
	$(this).find('.board_exe_ShowContextMenuComment').hide();
}

function GetImageFromAnalisedData(str)
{
	if(str.charAt(0)=='i')
	{
		return str.substr(1,str.length);
	}else{
		var split_str=str.split('_');
		return split_str[1];
	}
}

function GetVideoFromAnalisedData(str)
{
	if(str.charAt(0)=='i')
	{
		return "";
	}else{
		var split_str=str.split('_');
		return split_str[0].substr(1,str.length);
	}
}


function analiseLinkFunction()
{
	iCurrentALImage=0;
	iCountALImage=ConvertToInt($('#board_ext_link_count').text());
	
	
	$("#board_ext_load_img").show();	
	$("#board_ext_link_image").css('display', 'none').attr('src',GetImageFromAnalisedData($('#hiias_'+iCurrentALImage).val())).load(function(){
		$("#board_ext_load_img").hide();
		$(this).show();				
   })
	
	$("#board_ext_link_prev").attr('disabled', 'disabled');
	
	//Brak obrazow/filmow blokujemy przyciski nastepny/poprzedni
	if(iCountALImage<2)
		$("#board_ext_link_next").attr('disabled', 'disabled');

	
	$("#board_ext_link_checkbox").click(function(){
			if($(this).is(':checked')) 
			{
				$("#board_ext_link_image").hide();
				$("#exclinkformnavi").hide();

			}else{
				$("#board_ext_link_image").show();
				$("#exclinkformnavi").show();
			}	
		});
		
	$("#board_ext_link_image").error(function() {
    	//alert('Handler for .error() called.')
 	});
 			 	
	//Obsluga przycisku nastepny: 
	$("#board_ext_link_next").click(function()
	{
		if(iCurrentALImage<(iCountALImage-1))
			iCurrentALImage++;
			
		if(iCurrentALImage==(iCountALImage-1))
			$(this).attr('disabled', 'disabled');
			
		$("#board_ext_load_img").show();	
			
			$("#board_ext_link_image").css('display', 'none').attr('src',GetImageFromAnalisedData($('#hiias_'+iCurrentALImage).val())).load(function(){
				$("#board_ext_load_img").hide();
				$(this).show();				
            })
			
			$("#board_ext_link_prev").removeAttr('disabled');	
			$("#board_ext_link_cur_image").text(iCurrentALImage+1);

	});

	//Obsluga przycisku nastepny
	$("#board_ext_link_prev").click(function()
	{
		if(iCurrentALImage!=0)
			iCurrentALImage--;
			
		if(iCurrentALImage==0)
			$(this).attr('disabled', 'disabled');
			
		$("#board_ext_load_img").show();			
		$("#board_ext_link_image").css('display', 'none').attr('src',GetImageFromAnalisedData($('#hiias_'+iCurrentALImage).val())).load(function(){
			$("#board_ext_load_img").hide();
			$(this).show();
        });
			
		$("#board_ext_link_next").removeAttr('disabled');//Odblokujemy przycisk "poprzedni"
		$("#board_ext_link_cur_image").text(iCurrentALImage+1);//Zminiamy wartosc tekstu "1 z 12"
	});

}

function ShowContextMenu()
{	
	
	var offset = $(this).offset();
	var menuObj=$(this).next().clone();
	
	$(menuObj).appendTo('body');	
	
	
	$(menuObj).data('object',$(this).parents('.board_status_section').attr('id'));

	
	$(".board_status_menu").mouseleave(HideStatusMenu);
	
	$(".board_action_lock_status").click(ActionLockStatus);
	$(".board_action_hide_status").click(ActionHideStatus);
	$(".board_action_delete_status").click(ActionDeleteStatus);
	
	var iWidth=menuObj.width();
	var iHeight=menuObj.height();

	var x=offset.left-iWidth+$(this).width();
	
	menuObj.show().offset({ top: offset.top, left:  x });
	
	/*
	var offset = $(this).offset();
	var menuObj=$(this).next();
	
	//$(menuObj).appendTo('body');	
	
	var iWidth=menuObj.width();
	var iHeight=menuObj.height();

	var x=offset.left-iWidth+$(this).width();
	
	menuObj.show().offset({ top: offset.top, left:  x });
	*/
	return false;
}

function ShowVideo()
{	
	$(this).parent().parent().hide();	
	$(this).parent().parent().next().show();	
}


function ActionDeleteComment()
{
	ConfrimDialog(this,"Czy na pewno chcesz usunąć ten komęntarz?","Usuń komętarz",true,200,50,function(this_obj)
	{
		$.ajax({ type: 'POST',async:false,  url: $(this_obj).attr('href'),success:function(data)
		{
			var address=$(this_obj).attr('href');			
			var id=address.substring(address.lastIndexOf('/') + 1); 			
			$('#cm_'+id).remove();			
		}});		
	});
	return false;
}


function ActionDeleteStatus()
{	
	ConfrimDialog(this,"Czy na pewno chcesz usunąć ten post?","Usuń post",true,200,50,function(this_obj)
	{
		$.ajax({ type: 'POST',async:false,  url: $(this_obj).attr('href'),success: function(data)
		{	
			var address=$(this_obj).attr('href');			
			var id=address.substring(address.lastIndexOf('/') + 1); 			
			$('#st_'+id).remove();			
		}});		
	});
	return false;
}


function ActionHideStatus()
{	
	ConfrimDialog(this,"Czy na pewno chcesz ukryć ten post?","Ukrywanie postu",true,200,50,function(this_obj)
	{
		$.ajax({ type: 'POST',async:false,  url: $(this_obj).attr('href'),success:function(data)
		{	
			var address=$(this_obj).attr('href');			
			var id=address.substring(address.lastIndexOf('/') + 1); 			
			$('#st_'+id).remove();			
		}});		
	});
	return false;
}

function ActionLockStatus()
{	
	ConfrimDialog(this,"Czy na pewno chcesz blokować ten typ postów?","Blokowanie postów",true,200,50,function(this_obj)
	{
		$.ajax({ type: 'POST',async:false,  url: $(this_obj).attr('href'),success:function(data)
		{	
			var address=$(this_obj).attr('href');			
			var id=address.substring(address.lastIndexOf('/') + 1); 			
			$('#st_'+id).remove();			
		}});		
	});
	return false;

}



function SetupEvents()
{	
	//$(".board_status").unbind('mouseenter');
	//$(".board_status").unbind('mouseleave');
	//$(".board_exe_ShowContextMenu").unbind('click');
	//$(".board_status").unbind('mouseenter');
	//$(".board_status").unbind('mouseleave');
	//$(".board_comment").unbind('mouseenter');
	//$(".board_comment").unbind('mouseleave');
	//$(".board_video_image").unbind('click');
	//$(".board_add_coments").unbind('click');	
	//$(".board_image_object").unbind('click');
	//$(".board_new_commet_form").unbind('submit');
	//$(".board_status_menu").unbind('mouseleave');	
	//$(".board_new_comment_input").unbind('focus');
	//$(".board_new_comment_input").unbind('blur');
	//$(".board_action_lock_status").unbind('click');;
	//$(".board_action_hide_status").unbind('click');
	//$(".board_action_delete_status").unbind('click');	
	
	//$(".board_status").mouseenter(OnMouseOverStatus);
	//$(".board_status").mouseleave(OnMouseOutStatus);
	//$(".board_exe_ShowContextMenu").click(ShowContextMenu);
	//$(".board_status").mouseenter(OnMouseOverStatus);
	//$(".board_status").mouseleave(OnMouseOutStatus);
	//$(".board_comment").mouseenter(OnMouseOverStatus);
	//$(".board_comment").mouseleave(OnMouseOutStatus);
	//$(".board_video_image").click(ShowVideo);
	//$(".board_add_coments").click(ShowNewCommentInput);	
	//$(".board_image_object").click(ImageFullScreen);
	//$(".board_new_comment_input").blur(function(){$(this).parent().submit();});
	//$(".board_new_commet_form").submit(AddComment);
	//$(".board_status_menu").mouseleave(HideStatusMenu);	
	//$(".board_action_lock_status").click(ActionLockStatus);
	//$(".board_action_hide_status").click(ActionHideStatus);
	//$(".board_action_delete_status").click(ActionDeleteStatus);
	//$(".board_show_commets").click(ShowComments);
	//$(".board_show_commets").bind('click',ShowComments);
	//$(".board_show_commets").live('click',ShowComments);
}


function InitBoard()
{	
	$(".board_status_bar a").live('click',ShowComments);
	$(".board_action_lock_status").live('click',ActionLockStatus);
	$(".board_action_hide_status").live('click',ActionHideStatus);
	$(".board_action_delete_status").live('click',ActionDeleteStatus);
	$(".board_video_image").live('click',ShowVideo);
	$(".board_add_coments").live('click',ShowNewCommentInput);	
	$(".board_image_object").live('click',ImageFullScreen);
	$(".board_exe_ShowContextMenu").live('click',ShowContextMenu);
		
	$(".board_comment").live('mouseenter',OnMouseOverComment);
	$(".board_comment").live('mouseleave',OnMouseOutComment);
	$(".board_status").live('mouseenter',OnMouseOverStatus);
	$(".board_status").live('mouseleave',OnMouseOutStatus);
	$(".board_comment").live('mouseenter',OnMouseOverStatus);
	$(".board_comment").live('mouseleave',OnMouseOutStatus);
	$(".board_status_menu").live('mouseleave',HideStatusMenu);

	$(".board_exe_ShowContextMenuComment").live('click',ActionDeleteComment);


	$('#board_shere_status_form').show();
	$(' [placeholder] ').defaultValue();
	
	
//Określamy reguły walidacji 
	
	$('#board_shere_link_form').validate({
	
   		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();			
			if (errors) {				
				$("#board_error span").text('Wprowadź poprawne dane');
				$("#board_error").show();
			} else {
				$("#board_error").hide();
			}
		},

		rules: {
    		'board_link[link]': {url:true,required:true}
    	},
    	
   		messages: {
    		'board_link[link]': {url:"",required:""}
    	}
    });
    
	$('#board_shere_photo_form').validate({
	
   		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();			
			if (errors) {				
				$("#board_error span").text('Wprowadź poprawne dane');
				$("#board_error").show();
			} else {
				$("#board_error").hide();
			}
		},

		rules: {
    		'board_image[file]': {required:true}
    	},
    	
   		messages: {
    		'board_image[file]': {required:""}
    	}
    });
    
	$('#board_shere_file_form').validate({
	
   		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();			
			if (errors) {				
				$("#board_error span").text('Wprowadź poprawne dane');
				$("#board_error").show();
			} else {
				$("#board_error").hide();
			}
		},

		rules: {
    		'board_file[file]': {required:true}
    	},
    	
   		messages: {
    		'board_file[file]': {required:""}
    	}
    });
    
	$('#board_shere_status_form').validate({
	
   		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();			
			if (errors) {				
				$("#board_error span").text('Wprowadź poprawne dane');
				$("#board_error").show();
			} else {
				$("#board_error").hide();
			}
		},

		rules: {
    		'board_status[text]': {required:true}
    	},
    	
   		messages: {
    		'board_status[text]': {required:""}
    	}
    });


	var status_options = {
			beforeSubmit: function(formData, jqForm, options){
				var bIsValid=$(jqForm).valid();
				if(bIsValid)
				{
					$('#board_shere_box').hide();
					$('#board_shere_loading').show();
				}
    			return bIsValid;
    		},

            success:  function(data, statusText, xhr, $form){            
  
            		$('#board_shere_box').show();
					$('#board_shere_loading').hide();					
					
							try
  							{
  								var obj = jQuery.parseJSON(data);  								
  								
  								if (obj.error)
            					{
            						$('#board_shere_box').find('#board_error').text(obj.error);                  
               					} else { 
               						alert(obj.html+'fdf');
            						$('#board_status_items').prepend(obj.html);                   					            		
									$('#board_add_status_input').addClass('board_deactive_input');
            					}
            					
  							}catch(err)
  							{
  								
  								$("#board_error").hide();
                				if($($form).attr('id')=='board_shere_link_form')
                				{
                   					$($form).hide();
                   					$('#board_shere_body').append(data);
                   					analiseLinkFunction();
                   					
                   					
	                   					var options = {
											beforeSubmit: function(formData, jqForm, options){
											
												var imgvid=$('#hiias_'+iCurrentALImage).val();
												var dot_vid=GetVideoFromAnalisedData(imgvid); 
												var dot_img=GetImageFromAnalisedData(imgvid);												
												
												formData.splice(0,formData.length);
												formData.push({"name":'uri', "value": ((dot_vid!="")?dot_vid:dot_img) });
									           	formData.push({"name":'desc', "value": $('#exclinkformdesc').text() });
									            formData.push({"name":'title', "value": $('#exclinkformtitle').text() });
									            formData.push({"name":'page', "value": $('#exclinkformurl').text() });
									            formData.push({"name":'extd', "value": ((dot_vid!="")?dot_img:"") });
									            											
												return true;
								    		},
								
		            						success:  function(data, statusText, xhr, $form){
		            							$('#board_status_items').prepend(data);
		                   					}
                   						};
                   					$('#exclinkform').ajaxForm(options);
                   					
                   				}else{
                   					$('#board_status_items').prepend(data);
                   					SetupEvents();            		
									$('#board_add_status_input').addClass('board_deactive_input');
                   				}
  							}
			         		
            },
            resetForm: true
     };
     
        
     $('#board_shere_status_form').ajaxForm(status_options);
	 $('#board_shere_photo_form').ajaxForm(status_options);	
	 $('#board_shere_file_form').ajaxForm(status_options);
	 $('#board_shere_link_form').ajaxForm(status_options);
	
	
	$('#board_shere_submit_status').click(function(){
		$(this).parents('#board_shere_forms').children('#board_shere_body').children('.board_form').each(function(){
		
			if($(this).css('display')=='block')
			{
				$(this).submit();
			}
		});
		return false;
	});

	$('#board_shere_status').click(function(){				
		
		$("#board_error").hide();
		$(".board_form").hide();
		$("#exclinkform").remove();		
		$('#board_shere_status_form').show();
			
		$('.board_shere_menu_item').removeClass('board_active_menu');
		$('#board_shere_status').addClass('board_active_menu');	
;		
						
		return false;		
		
	});
	
	$('#board_shere_file').click(function(){				
				
		$(".board_form").hide();
		$("#exclinkform").remove();
		$('#board_shere_file_form').show();
		$("#board_error").hide();
		$('.board_shere_menu_item').removeClass('board_active_menu');
		$('#board_shere_file').addClass('board_active_menu');
		
		return false;
	});
	
	$('#board_shere_link').click(function(){				
		
		$(".board_form").hide();
		$("#exclinkform").remove();
		$('#board_shere_link_form').show();
		$("#board_error").hide();

		$('.board_shere_menu_item').removeClass('board_active_menu');	
		$('#board_shere_link').addClass('board_active_menu');
				
		return false;
	});


 	$('#board_shere_photo').click(function(){				
		
		$(".board_form").hide();
		$("#exclinkform").remove();
		$('#board_shere_photo_form').show();		
		$("#board_error").hide();
		$('.board_shere_menu_item').removeClass('board_active_menu');	
		$('#board_shere_photo').addClass('board_active_menu');
		
		return false;
	});
	
		
	$.post($('#board_recive').val(), function(data) {		
		$('#board_status_items').prepend(data);
		UpdateTimeDate();
		setInterval(function(){UpdateTimeDate();},5000);
		SetupEvents();
	});

}

function HideStatusMenu()
{
	$(this).remove();
}



var nazwy_mies = [ 'Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj','Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 
                   'Listopad', 'Grudzień' ];

var nazwy_dni=['niedziela','poniedziałek','wtorek','środa','czwartek','piątek','sobota'];

//Zaktualizuj czas na statusach i w komentarzach
function UpdateTimeDate()
{
	$("#board_status_items").children(".board_status_section").each(function() {
					
		//Aktalizacja czasu statusu
		$(this).find(".board_status_bar").each(function()
		{
			$(this).children('.board_status_time_field').text(transformDate($(this).children('.board_hidden_status_time').val()));			
		});		

		//Aktualizacja czasu widocznych kometarzy			
		$(this).find('.board_comment').each(function()
		{									
			var obj=$(this).find('.board_status_cbar');
			obj.children('.board_time_comemnt').text(transformDate(obj.children('.board_hidden_comment_time').val()));		
		});
		
	});	
}

//Gdy czasem ParseInt nie dziala 
function ConvertToInt(str)
{
	var k=0;
	for(var i=0;i<str.length;i++)
	{
		k+=(str[i]*Math.pow(10,str.length-i-1));
	}
	return k;
}

//Zamienia date na informacje jaki czas temu dodano post (do 24h)(ustawione dla testow co 5s)
//dt - data do zamiany
function transformDate(dt)
{	
	var str_rez="";
	var kt=dt.split(':');		
	Stamp = new Date();	
	var zero=(Stamp.getFullYear()-ConvertToInt(kt[2]))+(Stamp.getMonth()-ConvertToInt(kt[1])+1)+(Stamp.getDate()-ConvertToInt(kt[0]));
	
	if(zero==0)//Ten sam dzien
	{
		//Obliczamy roznice sekund miedzy aktualna data a utworzenia statusu
		var koka=(Stamp.getHours()-ConvertToInt(kt[3]))*3600+(Stamp.getMinutes()-ConvertToInt(kt[4]))*60+(Stamp.getSeconds()-ConvertToInt(kt[5]));
		
		if(koka<60)
		{
			str_rez=koka+' sekund(y) temu';
		}else if(koka<3600)
		{
			str_rez=Math.floor(koka/60)+' minut(y) temu';
		}else{
			str_rez=Math.floor(koka/3600)+' godz. temu';
		}

	}else{//Ponad 24h, wiec wyswietlamy date normalnie (gdy rok utworzenia i aktualny jest taki sam to wyswietlanie roku jest pomijane)
		str_rez=(kt[0]+' '+nazwy_mies[ConvertToInt(kt[1])-1]+' '+((Stamp.getFullYear()!=kt[2])?kt[2]:""));
	}
	
	return str_rez;
}


function ShowNewCommentInput(event)
{		
	event.preventDefault();
	
	var obj=$(this).parents('.board_status_section').find('.board_new_comment');
	if(obj.css('display')=='none')
	{		
		
		var val_options = {
	
   		invalidHandler: function(e, validator) {
			
		},

		rules: {
    		'board_comment[text]': {required:true}
    	},
    	
   		messages: {
    		'board_comment[text]': {required:""}
    	}
    };

		
		
		var comment_options = {
			beforeSubmit: function(formData, jqForm, options){
				return	$(jqForm).valid();
    		},

            success:  function(data, statusText, xhr, $form){  
            		
            		try
  					{
  						var obj = jQuery.parseJSON(data);
  						if (obj)
            			{
            				//alert(obj.error);                  
               			} else { 
            				$form.parent().parent().children('.board_comments').append(data);
            			}
  					}catch(err)
  					{
  						$form.parent().parent().children('.board_comments').append(data);

  					}
  					            	
            },
            resetForm: true
    	 };  
    	         
        obj.children(".board_new_commet_form").validate(val_options);
     	obj.children(".board_new_commet_form").ajaxForm(comment_options);
     	
     	obj.show();
		
	}	
	return false;
}

//Wychodzimy z trybu pelnoekranowego powiekszania zdiecia
function ImageFullScreenClose()
{	
	$(this).parent().remove();
}

//Powiekszamy klikniety obrazek
function ImageFullScreen()
{
	$("#board_status_items").append(
	'<div>'+
	'<div class="fullscreendivbackground">'+
	'</div>'+
	'<div class="fullscreendiv">'+
	'<img class="fullscreendivimage" src="'+$(this).attr("src")+'" />'+
	'</div>'+
	'</div>');
	
	 var halfsc = $(window).height()/2;
	 var halfscrn = $(window).width()/2;
	 var objw = $(".fullscreendivimage").width()/2;
	 var objh = $(".fullscreendivimage").height()/2;
	 
	$(".fullscreendivbackground").height($("body").height()+60);
	 
	$(".fullscreendivbackground").click(ImageFullScreenClose);
	$(".fullscreendiv").offset({ top: (halfsc-objh)+$(window).scrollTop(), left: (halfscrn-objw) });	
}


function ShowComments(event)
{	
	event.preventDefault();

	var jObj=$(this).parents(".board_status_section").children(".board_comment_section").children(".board_comments");

	if($(this).text().indexOf("Pokaż",0)!=-1)
	{	
		
		$.post($(this).attr('href'),function(data)
		{								
				jObj.empty();
				jObj.append(data);
				//jObj.children('.board_new_comment').before('<b>duperele</b>');	
					//jObj.children('.board_new_comment').before(data);	
		});
		
		$(this).text("Ukryj komentarze");
		
	}else{
		var count=jObj.children(".board_comment").length;		
		$(this).text("Pokaż komentarze ("+count+")");
		//jObj.remove(":not(:first)");
		var temp =jObj.children(":last").clone(true);	
		jObj.empty();
		jObj.append(temp);
		
	}
	
	return false;
}
